//
//  ScanViewController.m
//  carcareIOS
//
//  Created by ileo on 15/6/2.
//  Copyright (c) 2015年 baozun. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ScannerView.h"

@interface ScanViewController () <AVCaptureMetadataOutputObjectsDelegate, UINavigationControllerDelegate, UIViewControllerNavBackgroundDataSource>

@property (nonatomic, strong) AVCaptureSession *session;

@property (nonatomic, strong) ScannerView *scanView;

@end

@implementation ScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!SYSTEMHELPER.isOpenMedia) {
        TipsView *tips = [TipsView textTipsWithTitle:LOCSTRING(@"tips_media_no_open") lightTitles:@[LOCSTRING(@"tips_media_open_1"),LOCSTRING(@"tips_media_open_2")]];
        [tips addOKButton:LOCSTRING(@"ok") clickOK:^{
            [AlertMgr dismiss:TYPE_VIEW_ALERT];
        }];
        [AlertMgr showView:tips];
        return;
    }
    
    self.view.backgroundColor = [UIColor blackColor];
    
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.extendedLayoutIncludesOpaqueBars = YES;
    self.modalPresentationCapturesStatusBarAppearance = YES;
    
    __weak __typeof(self) wself = self;
    [self navSetupLeftTitle:@"取消" action:^{
        [wself dismissViewControllerAnimated:YES completion:nil success:NO info:nil];
    }];
    
    //获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc]init];
    //设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //初始化链接对象
    self.session = [[AVCaptureSession alloc]init];
    //高质量采集率
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [self.session addInput:input];
    [self.session addOutput:output];
    //设置扫码支持的编码格式(如下设置条形码和二维码兼容)
    output.metadataObjectTypes=@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
    //扫描区域
    CGRect scanRect = CGRectMake((__MAIN_WIDTH - 200) / 2, __MAIN_HEIGHT_64/2 - 100, 200, 200);
    
    output.rectOfInterest=CGRectMake(scanRect.origin.y / self.view.height, scanRect.origin.x / self.view.width, scanRect.size.height / self.view.height, scanRect.size.width / self.view.width);
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    layer.videoGravity=AVLayerVideoGravityResizeAspectFill;
    layer.frame=self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    //开始捕获
    [self.session startRunning];

    self.scanView = [[ScannerView alloc] initWithFrame:self.view.bounds withScanRect:scanRect];
    [self.view addSubview:self.scanView];
    [self.scanView lineAnimation];
    
    // Do any additional setup after loading the view, typically from a nib.
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects.count>0) {
        //[session stopRunning];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex : 0 ];
        //输出扫描字符串
        
        if ([Check isDevice:metadataObject.stringValue]) {
            USERINFO.device = metadataObject.stringValue;
            [self.session stopRunning];
            
            [self dismissViewControllerAnimated:YES completion:nil success:YES info:nil];

        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIColor *)navBackgroundColor{
    return [[UIViewController navBackgroundColor] colorWithAlphaComponent:0.3];
}

@end
